<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php	
class RouteSchedulesController extends AppController {

	var $name = 'RouteSchedules';
	var $uses = array('RouteSchedule','RouteScheduleCode', 'TimeSchedule', 'RouteNodeAssoc', 'RouteScheduleNodeAssoc', 'Trip', 'TripInfo', 'MediaPlan', 'MediaPlanSlot', 'TelematicUnit');

	function index() {
		list($order, $limit, $page) = $this->setupPagination();
		$this->set('routeSchedules', $this->RouteSchedule->findAll(NULL, NULL, $order, $limit, $page));
		$weekDays = array(
				-1 => 'Daily',
				1 => 'Sunday',
				2 => 'Monday',
				3 => 'Tuesday',
				4 => 'Wednesday',
				5 => 'Thursday',
				6 => 'Friday',
				7 => 'Saturday',
			);
			$this->set('weekDays', $weekDays);
	}

	function view($id = null) {
		$this->checkRecordExistance($id);
		$this->set('routeSchedule', $this->RouteSchedule->read(null, $id));
		$weekDays = array(
			-1 => 'Daily',
			1 => 'Sunday',
			2 => 'Monday',
			3 => 'Tuesday',
			4 => 'Wednesday',
			5 => 'Thursday',
			6 => 'Friday',
			7 => 'Saturday',
		);
		$this->set('weekDays', $weekDays);
		$routeScheduleNodeAssocs = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$id));
		if(empty($routeScheduleNodeAssocs )){
			$routeScheduleNodeAssocs  = array();
		}
		$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$id));
		$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
		usort($routeScheduleNodeAssocs, array("RouteSchedulesController", "nodeOrderSort")); 
		$this->set('timeSchedules', $routeScheduleNodeAssocs );
	}

	function add() {
		if (empty($this->data)) {
			// Template part
			if (!is_array($routeScheduleTemplates = $this->RouteSchedule->generateList(array('route_schedule_status'=>1), 'route_schedule_code ASC'))){
				$routeScheduleTemplates = array();
			}
			$routeScheduleTemplates[0] = " None";
			asort($routeScheduleTemplates);
			$this->set('routeScheduleTemplates', $routeScheduleTemplates);
			if (!is_array($routes = $this->RouteSchedule->Route->generateList(NULL, 'route_name ASC'))){
				$routes = array();
			}
			foreach ($routes as $routeId => $routeCode) {
				$routeName = $this->RouteSchedule->Route->field('Route.route_name', "Route.id =".$routeId);
				$routes[$routeId] = $routeName.' ('.$routeCode.')';
			}
			asort($routes);
			$this->set('routes', $routes);
			$weekDays = array(
				-1 => 'Daily',
				1 => 'Sunday',
				2 => 'Monday',
				3 => 'Tuesday',
				4 => 'Wednesday',
				5 => 'Thursday',
				6 => 'Friday',
				7 => 'Saturday',
			);
			$this->set('weekDays', $weekDays);
			$this->render();
		} else {
			$this->cleanupData();
			$this->data['RouteSchedule']['route_schedule_code'] = low($this->data['RouteSchedule']['route_schedule_code']);
			$this->RouteSchedule->begin();
			$this->RouteScheduleCode->begin();
			$this->RouteScheduleNodeAssoc->begin();
			$this->TimeSchedule->begin();
			$allowCommit  = true;
			if ($this->data['RouteSchedule']['route_schedule_import'] && $this->data['RouteSchedule']['route_schedule_code']) {
				if ($this->import($this->data['RouteSchedule']['route_schedule_import'], $this->data['RouteSchedule']['import_media_plan'])) {
					$this->RouteScheduleNodeAssoc->commit();
					$this->RouteSchedule->commit();
					$this->RouteScheduleCode->commit();
					$this->TimeSchedule->commit();
					$this->Session->setFlash('Route schedule imported successfully.', 'message_ok');
					$this->redirect('/route_schedules/view/'.$this->RouteSchedule->getLastInsertID());
					// Since we are explicitly calling exit() function
					// So afterFilter will not be called automatically 
					$this->afterFilter();
					exit(0);
				} else {
					$allowCommit = false;
					$this->RouteScheduleNodeAssoc->rollback();
					$this->RouteScheduleCode->rollback();
					$this->RouteSchedule->rollback();
					$this->TimeSchedule->rollback();
					// Since we are explicitly calling exit() function
					// So afterFilter will not be called automatically 
					$this->afterFilter();
					//$this->Session->setFlash('Route schedule import failed.', 'message_error');
					$this->redirect('/route_schedules/index');
					exit(0);
				}
			}
			if ($this->RouteSchedule->save($this->data)) {
				$routeScheduleId = $this->RouteSchedule->getLastInsertID();
				$routeScheduleCodeFields['RouteScheduleCode.route_schedule_code'] = $this->data['RouteSchedule']['route_schedule_code'];
				if (!$this->RouteScheduleCode->hasAny($routeScheduleCodeFields)) {
					$routeScheduleCodeData['RouteScheduleCode']['route_schedule_id'] = $routeScheduleId;
					$routeScheduleCodeData['RouteScheduleCode']['route_schedule_code']   = $this->data['RouteSchedule']['route_schedule_code'];
					if (!$this->RouteScheduleCode->save($routeScheduleCodeData)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating Route schedule code list.', 'message_error');
					}
				} else {
					$allowCommit = false;
					$this->Session->setFlash('Route schedule code already exists in Route schedule codes list.', 'message_error');
				}
				if($allowCommit) {
					$routeId = $this->data['RouteSchedule']['route_id'];
					$routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId));
					foreach ($routeNodeAssocs as $routeNodeAssoc){
						unset($RouteScheduleNodeAssocData);
						$routeScheduleNodeAssocData['RouteScheduleNodeAssoc']['id'] = null;
						$routeScheduleNodeAssocData['RouteScheduleNodeAssoc']['route_schedule_id'] = $routeScheduleId;
						$routeScheduleNodeAssocData['RouteScheduleNodeAssoc']['node_id'] = $routeNodeAssoc['RouteNodeAssoc']['node_id'];
						if (!$this->RouteScheduleNodeAssoc->save($routeScheduleNodeAssocData)) {
							$allowCommit  = false;
							$this->Session->setFlash('Error in saving Node schedule.', 'message_error');
						}
						$rsnaId = $this->RouteScheduleNodeAssoc->getLastInsertID();
						unset($mediaPlanData); 
						$mediaPlanData['MediaPlan']['id'] = null; 
						$mediaPlanData['MediaPlan']['media_plan_code'] = 'mp-'.$this->data['RouteSchedule']['route_schedule_code']."-".$routeNodeAssoc['RouteNodeAssoc']['node_id']; 
						$mediaPlanData['MediaPlan']['media_plan_title'] = 'Plan for '.$this->data['RouteSchedule']['route_schedule_code']."-".$routeNodeAssoc['RouteNodeAssoc']['node_id']; 
						$mediaPlanData['MediaPlan']['route_schedule_node_assoc_id'] = $rsnaId; 
						if (!$this->MediaPlan->save($mediaPlanData)) {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Media plan for the Route schedule.', 'message_error');
							break;
						}
					}
				}
				if ($allowCommit) {
					// TODO Create media plan for the route schedule	
				}
				
			} else {
				$allowCommit = false;
				$this->Session->setFlash('Please correct errors below.', 'message_error');
			}
			if ($allowCommit) {
				$this->RouteScheduleNodeAssoc->commit();
				$this->RouteScheduleCode->commit();
				$this->RouteSchedule->commit();
				$this->TimeSchedule->commit();
				$this->Session->setFlash('Now please schedule nodes for the new route schedule', 'message_ok');
				$this->redirect('/route_schedules/edit/'.$routeScheduleId.'/1');
			} else {
				$this->RouteScheduleNodeAssoc->rollback();
				$this->RouteSchedule->rollback();
				$this->RouteScheduleCode->rollback();
				$this->TimeSchedule->rollback();
				// Template part
				if (!is_array($routeScheduleTemplates = $this->RouteSchedule->generateList(array('route_schedule_status'=>1), 'route_schedule_code ASC'))){
					$routeScheduleTemplates = array();
				}
				$routeScheduleTemplates[0] = " None";
				asort($routeScheduleTemplates);
				$this->set('routeScheduleTemplates', $routeScheduleTemplates);
				if (!is_array($routes = $this->RouteSchedule->Route->generateList(NULL, 'route_code ASC'))){
					$routes = array();
				}
				foreach ($routes as $routeId => $routeCode) {
					$routeName = $this->RouteSchedule->Route->field('Route.route_name', "Route.id =".$routeId);
					$routes[$routeId] = $routeName.' ('.$routeCode.')';
				}
				asort($routes);
				$this->set('routes', $routes);
				$weekDays = array(
					-1 => 'Daily',
					1 => 'Sunday',
					2 => 'Monday',
					3 => 'Tuesday',
					4 => 'Wednesday',
					5 => 'Thursday',
					6 => 'Friday',
					7 => 'Saturday',
				);
				$this->set('weekDays', $weekDays);
			}
		}
	}
	
	/**
	 * Just a confirmation screen for now
	 *
	 * @param unknown_type $id
	 */
	function confirm_edit($id) {
		
		if (empty($this->data)) {
			$this->set('routeScheduleId', $id);
			$this->set('routeScheduleName', $this->RouteSchedule->field('RouteSchedule.route_schedule_name', "RouteSchedule.id =".$id));
			$this->render('confirm_edit');
			exit(0);
		} else {
			$this->checkJavaScript();
			if ($this->data['RouteSchedule']['confirm']) {
				unset($this->data);
				$this->edit($id, 1);
				exit(0);
			} else {
				$this->edit($id, 0);
				exit(0);
			}
		}
		
	}
	
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $id
	 * @param unknown_type $confirm
	 */
	function edit ($id = null, $confirm = null) {
		
		if ($confirm === null){
			$this->confirm_edit($id);
			exit(0);
		} else if ($confirm === 0) {
			$this->Session->setFlash('Operation cancelled by user.', 'message_ok');
			$this->redirect('/route_schedules/index');
			exit(0);
		} else {
			/*
			// Delete All mediaplan entries associated with this route
			$this->MediaPlan->recursive = 1;
			if (!is_array($mediaPlans = $this->MediaPlan->findAll(array('RouteScheduleNodeAssoc.route_schedule_id' => $id)))) {
				$mediaPlans = array();
			}
			$this->MediaPlan->begin();
			$allowCommit= true;
			foreach ($mediaPlans as $mediaPlan) {
				if (!$this->MediaPlan->del($mediaPlan['MediaPlan']['id'])){
					$allowCommit = false;
				} else {
					$this->Session->setFlash('The Media plan(s) deleted.', 'message_ok');
				}
			}
			if ($allowCommit) {
				$this->MediaPlan->commit();
			} else {
				$this->MediaPlan->rollback();
				$this->redirect('/route_schedules/index');
			}
			*/
			
		}
		
		if (empty($this->data)) {
			$this->checkRecordExistance($id);
			$this->data = $this->RouteSchedule->read(null, $id);
			$route_id   = $this->RouteSchedule->field('Route.id', "RouteSchedule.id =".$id);
			$route_name = $this->RouteSchedule->field('Route.route_name', "RouteSchedule.id =".$id);
			$this->set('route_id', $route_id);
			$this->set('route_name', $route_name);
			$weekDays = array(
				-1 => 'Daily',
				//0 => 'Not Scheduled',
				1 => 'Sunday',
				2 => 'Monday',
				3 => 'Tuesday',
				4 => 'Wednesday',
				5 => 'Thursday',
				6 => 'Friday',
				7 => 'Saturday',
			);
			$this->set('weekDays', $weekDays);
			$routeScheduleNodeAssocs = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$id));
			if(empty($routeScheduleNodeAssocs )){
				$routeScheduleNodeAssocs  = array();
			}
			$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$id));
			$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
			usort($routeScheduleNodeAssocs, array("RouteSchedulesController", "nodeOrderSort")); 
			$this->set('timeSchedules', $routeScheduleNodeAssocs );
			$this->render('edit');
			
		} else {
			$this->cleanupData();
			//$this->data['RouteSchedule']['route_schedule_code'] = low($this->data['RouteSchedule']['route_schedule_code']);
			// To prevent media vendor code modification by any malpractice
			$this->data['RouteSchedule']['route_schedule_code'] = $this->RouteSchedule->field('route_schedule_code', "RouteSchedule.id =".$id);
			$this->RouteSchedule->begin();
			$this->MediaPlan->begin();
			$this->TimeSchedule->begin();
			if ($this->RouteSchedule->save($this->data)) {
				$route_schedule_id = $this->data['RouteSchedule']['id'];
				$routeScheduleNodeAssocs = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$id));
				$allowCommit      = true;
				$firstTimeInLoop  = true;
				if (array_key_exists('TimeSchedule', $this->data)) {
					foreach ($routeScheduleNodeAssocs as $rsna) {
						$nodeId = $rsna['RouteScheduleNodeAssoc']['node_id'];
						$timeScheduleData['TimeSchedule']['route_schedule_node_assoc_id'] = $rsna['RouteScheduleNodeAssoc']['id'];
						if(!isset($this->data['TimeSchedule']['time_schedule_arrival_time'.  $nodeId.'_hour']) ||
							!isset($this->data['TimeSchedule']['time_schedule_arrival_time'.  $nodeId.'_min']) ||
							!isset($this->data['TimeSchedule']['time_schedule_departure_time'. $nodeId.'_hour']) ||
							!isset($this->data['TimeSchedule']['time_schedule_departure_time'. $nodeId.'_min']) ||
							!isset($this->data['TimeSchedule']['time_schedule_departure_time'.  $nodeId.'_sec']) 
						) {
							$allowCommit = false;
							$this->Session->setFlash('Please fill time for all nodes.', 'message_error');
							break;
						}
						
						$arrivalTime   = $this->data['TimeSchedule']['time_schedule_arrival_time'.  $nodeId.'_hour'].":".$this->data['TimeSchedule']['time_schedule_arrival_time'.  $nodeId.'_min'].":".$this->data['TimeSchedule']['time_schedule_arrival_time'.    $nodeId.'_sec'];
						$departureTime = $this->data['TimeSchedule']['time_schedule_departure_time'.$nodeId.'_hour'].":".$this->data['TimeSchedule']['time_schedule_departure_time'.$nodeId.'_min'].":".$this->data['TimeSchedule']['time_schedule_departure_time'.  $nodeId.'_sec'];
						$arrivalDay    = $this->data['TimeSchedule']['time_schedule_arrival_day'.   $nodeId];
						$departureDay  = $this->data['TimeSchedule']['time_schedule_departure_day'. $nodeId];
					
						$timeScheduleData['TimeSchedule']['time_schedule_arrival_time']    = $arrivalTime; 
						$timeScheduleData['TimeSchedule']['time_schedule_departure_time']  = $departureTime; 
						$timeScheduleData['TimeSchedule']['time_schedule_arrival_day']     = $arrivalDay; 
						$timeScheduleData['TimeSchedule']['time_schedule_departure_day']   = $departureDay;
						 
						if($firstTimeInLoop){
							$scheduleStartTime = $arrivalTime;
							$firstTimeInLoop = false;
						}
						$scheduleEndTime = $departureTime;
						
						unset($fields);
						$fields['route_schedule_node_assoc_id'] = $rsna['RouteScheduleNodeAssoc']['id']; 
						if($this->TimeSchedule->hasAny($fields)) {
							// Get id of this entry 
							$entryId = $this->TimeSchedule->field('TimeSchedule.id', $fields);
							$timeScheduleData['TimeSchedule']['id'] = $entryId;
						} else {
							$timeScheduleData['TimeSchedule']['id'] = null;
						}
						if(!$this->TimeSchedule->save($timeScheduleData)){
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Node schedule.', 'message_error');
							break;
						}
						/*
						// Create Mediaplan for this Route schedule node Assoc entry
						unset($mediaPlanData); 
						$mediaPlanData['MediaPlan']['id'] = null; 
						$mediaPlanData['MediaPlan']['media_plan_code'] = 'mp-'.$this->data['RouteSchedule']['route_schedule_code']."-".$rsna['Node']['id']; 
						$mediaPlanData['MediaPlan']['media_plan_title'] = 'Plan for '.$this->data['RouteSchedule']['route_schedule_code']."-".$rsna['Node']['id']; 
						$mediaPlanData['MediaPlan']['route_schedule_node_assoc_id'] = $rsna['RouteScheduleNodeAssoc']['id']; 
						if (!$this->MediaPlan->save($mediaPlanData)) {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Media plan for the Route schedule.', 'message_error');
							break;
						}
						*/
						
					}
					if ($allowCommit) {
						if (!$this->RouteSchedule->saveField('route_schedule_start_time', $scheduleStartTime)) {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Route schedule.', 'message_error');
						}
						if (!$this->RouteSchedule->saveField('route_schedule_end_time', $scheduleEndTime)) {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Route schedule.', 'message_error');
						}
						if (!$this->RouteSchedule->saveField('route_schedule_status', 1)) {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Route schedule status.', 'message_error');
						}
						if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$id)) > 0) {
							if (!$this->pushToTripInfoQueue($id, false)) {
								$allowCommit = false;
								$this->Session->setFlash('Error while updating trip info queue, The Route schedule not deleted.', 'message_error');
							}
						}
					}
				
				} else{
					$allowCommit = false;
					$this->Session->setFlash('Node schedule details not availabele.', 'message_error');
				}
				if($allowCommit){
					
				}
				if($allowCommit){
					$this->TimeSchedule->commit();
					$this->RouteSchedule->commit();
					$this->MediaPlan->commit();
					$this->Session->setFlash('The Route schedule has been saved.', 'message_ok');
					$this->redirect('/route_schedules/index');
				} else {
					//$this->Session->setFlash('Node schedule error.', 'message_error');
					$this->redirect('/route_schedules/edit/'.$route_schedule_id);
				}
			} else {
				$this->TimeSchedule->rollback();
				$this->RouteSchedule->rollback();
				$this->MediaPlan->rollback();
				$this->Session->setFlash('Please correct errors below.', 'message_error');
				$route_id   = $this->RouteSchedule->field('Route.id', "RouteSchedule.id =".$id);
				$route_name = $this->RouteSchedule->field('Route.route_name', "RouteSchedule.id =".$id);
				$this->set('route_id', $route_id);
				$this->set('route_name', $route_name);
				$weekDays = array(
					-1 => 'Daily',
					//0 => 'Not Scheduled',
					1 => 'Sunday',
					2 => 'Monday',
					3 => 'Tuesday',
					4 => 'Wednesday',
					5 => 'Thursday',
					6 => 'Friday',
					7 => 'Saturday',
				);
				$this->set('weekDays', $weekDays);
			}
		}
		
	}
	
	/**
	 * List all trips associated with this route schedule 
	 * and let the user an option for go ahead with deleting all associated trips
	 *
	 * @param unknown_type $id
	 */
	function confirm_delete($id) {
		
		
		if (empty($this->data)) {
			$this->set('route_schedule_id', $id);
			$this->set('route_schedule_name', $this->RouteSchedule->field('RouteSchedule.route_schedule_name', "RouteSchedule.id =".$id));
			$this->Trip->recursive = 2;
			if (!is_array($trips = $this->Trip->findAll(array('Trip.route_schedule_id' => $id)))) {
				$trips = array();
			}
			if (count($trips) == 0) {
				$this->delete($id, 1);
				exit(0);
			}		
			$this->set('trips', $trips);
			$this->render('confirm_delete');
			exit(0);
		} else {
			if ($this->data['RouteSchedule']['confirm']) {
				unset($this->data);
				$this->delete($id, 1);
				exit(0);
			} else {
				$this->delete($id, 0);
				exit(0);
			}
		}
		
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $id
	 */
	function delete($id = null, $confirm = null) {
		
		if ($confirm === null){
			$this->confirm_delete($id);
			exit(0);
		} else if ($confirm === 0) { 	// Note the use of '==='
			$this->Session->setFlash('Operation cancelled by user.', 'message_ok');
			$this->redirect('/route_schedules/index');
			exit(0);
		}
		$this->RouteSchedule->begin();
		$this->RouteScheduleCode->begin();
		$this->TripInfo->begin();
		$allowCommit = true;
		$hasAssociatedTrips = false;
		
		// Delete All trips associated with this route schedule.
			$this->Trip->recursive = 1;
			if (!is_array($trips = $this->Trip->findAll(array('Trip.route_schedule_id' => $id)))) {
				$trips = array();
			}
			foreach ($trips as $trip) {
				$hasAssociatedTrips = true;
				// Delete trip
				if (!$this->Trip->del($trip['Trip']['id'])) {
					$allowCommit = false;
					$this->Session->setFlash('Unable to delete trip(s) associated with this route schedule.', 'message_error');
				}
			}
			
		$this->checkRecordExistance($id);
		$fields['Trip.route_schedule_id'] = $id; 
		//$fields['Trip.trip_status'] = "S";
		if($this->Trip->hasAny($fields)){
			// Active trip with this route schedule exists.
	//		$this->Session->setFlash('A trip with this route schedule is active. Please end or cancel that trip inorder to delete this route schedule.', 'message_error');
			$this->Session->setFlash('One or more trip with this route schedule is present. Please delete all those trips in order to delete this route schedule.', 'message_error');
			$this->redirect('/route_schedules/view/'.$id);
			exit(0);
		}
		if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$id)) > 0) {
			if (!$this->pushToTripInfoQueue($id, true)) {
				$allowCommit = false;
				$this->Session->setFlash('Error while updating trip info queue, The Route schedule not deleted.', 'message_error');
			}
		}
		if ($this->RouteSchedule->del($id)) {
			$routeScheduleCodeListEntry = $this->RouteScheduleCode->find(array("RouteScheduleCode.route_schedule_id" => $id));
			$routeScheduleCodeListEntry['RouteScheduleCode']['route_schedule_deleted'] = 1;
			if (!$this->RouteScheduleCode->save($routeScheduleCodeListEntry)) {
				$allowCommit = false;
				$this->Session->setFlash('Error while updating Route schedule code list, schedule not deleted.', 'message_error');
			}
			if ($allowCommit) {
				$this->RouteSchedule->commit();
				$this->RouteScheduleCode->commit();
				$this->TripInfo->commit();
				if ($hasAssociatedTrips) {
					$this->Session->setFlash('The Route schedule and associated trip(s) deleted.', 'message_ok');
				} else {
					$this->Session->setFlash('The Route schedule deleted.', 'message_ok');
				}
				$this->redirect('/route_schedules/index');
			} else {
				$this->RouteSchedule->rollback();
				$this->RouteScheduleCode->rollback();
				$this->TripInfo->rollback();
				$this->redirect('/route_schedules/index');
			}
		} else {
			$this->RouteSchedule->rollback();
			$this->RouteScheduleCode->rollback();
			$this->TripInfo->rollback();
			$this->showError(ERROR_DELETE, 'Unable to delete record.');
		}
	}
	
	/**
	 * If a Route schedule is deleted, a new trip info id is generated with 'route_schedule_deleted' set 
	 * and all the ivtu(vehicles) codes are collected and stored in 'vehicle_list' field.
	 *
	 * @param unknown_type $routeScheduleId
	 * @return unknown
	 */
	function pushToTripInfoQueue($routeScheduleId, $deleted) {
		
		if ($deleted) {
			//  To get TU List
			$tuList = "";
			$vehicles = $this->Trip->findAll(array('Trip.route_schedule_id'=>$routeScheduleId));
			foreach ($vehicles as $vehicle) {
				$telematicUnits = $this->TelematicUnit->findAll(array('Vehicle.id'=>$vehicle['Vehicle']['id'], 'TelematicUnit.telematic_unit_location_type'=>'v'), 'TelematicUnit.telematic_unit_code');
				foreach ($telematicUnits as $telematicUnit) {
					$tuList .= $telematicUnit['TelematicUnit']['telematic_unit_code']. ",";
				}
			}
			
			// Remove the last comma from the TU List
			$tuList = substr($tuList, 0, -1);
			
			$data['TripInfo']['route_schedule_id'] = $routeScheduleId;
			$data['TripInfo']['route_schedule_deleted'] = 1;
			$data['TripInfo']['vehicle_list'] = $tuList;
			return $this->TripInfo->save($data);
		} else {
			$flag = true;
			$trips = $this->Trip->findAll(array('Trip.route_schedule_id'=>$routeScheduleId));
			foreach ($trips as $trip) {
				$field['TripInfo.trip_info_reference'] = $trip['Trip']['id'];
				if($this->TripInfo->hasAny($field)) {
					return true;
				} else {
					$data['TripInfo']['trip_info_reference'] = $trip['Trip']['id'];
					$data['TripInfo']['vehicle_id']          = $trip['Trip']['vehicle_id'];
					$data['TripInfo']['route_schedule_id']   = $trip['Trip']['route_schedule_id'];
					if(!$this->TripInfo->save($data)) {
						$flag = false;
					}
				}
				
			}
			return $flag;		
		}
		
	}
	
	function import($templateId, $mediaPlanImport=false) {
		
		//return false;
		
		$this->RouteSchedule->recursive = 0;
		$routeScheduleTemplate = $this->RouteSchedule->find(array('RouteSchedule.id'=>$templateId));
		if(is_array($routeScheduleTemplate) && count($routeScheduleTemplate) > 0){
			$importedData['RouteSchedule']['route_id']                  = $routeScheduleTemplate['RouteSchedule']['route_id'];	
			$importedData['RouteSchedule']['route_schedule_code']       = $this->data['RouteSchedule']['route_schedule_code'];	
			$importedData['RouteSchedule']['route_schedule_name']       = $this->data['RouteSchedule']['route_schedule_name'];	
			$importedData['RouteSchedule']['route_schedule_start_day']  = $routeScheduleTemplate['RouteSchedule']['route_schedule_start_day'];	
			$importedData['RouteSchedule']['route_schedule_start_time'] = $routeScheduleTemplate['RouteSchedule']['route_schedule_start_time'];	
			$importedData['RouteSchedule']['route_schedule_end_time']   = $routeScheduleTemplate['RouteSchedule']['route_schedule_end_time'];	
			$importedData['RouteSchedule']['route_schedule_status']     = $routeScheduleTemplate['RouteSchedule']['route_schedule_status'];
			if($this->RouteSchedule->save($importedData)) {
				$routeScheduleId = $this->RouteSchedule->getLastInsertID();
				$routeScheduleCodeFields['RouteScheduleCode.route_schedule_code'] = $this->data['RouteSchedule']['route_schedule_code'];
				if (!$this->RouteScheduleCode->hasAny($routeScheduleCodeFields)) {
					$routeScheduleCodeData['RouteScheduleCode']['route_schedule_id'] = $routeScheduleId;
					$routeScheduleCodeData['RouteScheduleCode']['route_schedule_code']   = $this->data['RouteSchedule']['route_schedule_code'];
					if (!$this->RouteScheduleCode->save($routeScheduleCodeData)) {
						$this->Session->setFlash('Error while updating Route schedule code list.', 'message_error');
						return false;
					}
				} else {
					$this->Session->setFlash('Route schedule code already exists in Route schedule codes list.', 'message_error');
					return false;
				}
				
				$rsnaTemplates = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$templateId));
				$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$templateId));
				$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
				usort($rsnaTemplates, array("RouteSchedulesController", "nodeOrderSort")); 
				
				// Create Route schedule node assocs entries from template
				$rsnaTemplateIdList = "";
				$rsnaMapMatrix      = array();
				foreach ($rsnaTemplates as $rsnaTemplate) {
					$rsnaData['RouteScheduleNodeAssoc']['id']                = null;
					$rsnaData['RouteScheduleNodeAssoc']['route_schedule_id'] = $routeScheduleId;
					$rsnaData['RouteScheduleNodeAssoc']['node_id']           = $rsnaTemplate['RouteScheduleNodeAssoc']['node_id'];
					$rsnaTemplateIdList .= $rsnaTemplate['RouteScheduleNodeAssoc']['id']. ",";
					if(!$this->RouteScheduleNodeAssoc->save($rsnaData)){
						$this->Session->setFlash('Error while importing Route schedule template.', 'message_error');
						return false;
					} 
					$rsnaId = $this->RouteScheduleNodeAssoc->getLastInsertID();
					$rsnaMapMatrix[$rsnaTemplate['RouteScheduleNodeAssoc']['id']] = $rsnaId;
					unset($mediaPlanData); 
					$mediaPlanData['MediaPlan']['id'] = null; 
					$mediaPlanData['MediaPlan']['media_plan_code'] = 'mp-'.$this->data['RouteSchedule']['route_schedule_code']."-".$rsnaTemplate['RouteScheduleNodeAssoc']['node_id']; 
					$mediaPlanData['MediaPlan']['media_plan_title'] = 'Plan for '.$this->data['RouteSchedule']['route_schedule_code']."-".$rsnaTemplate['RouteScheduleNodeAssoc']['node_id']; 
					$mediaPlanData['MediaPlan']['route_schedule_node_assoc_id'] = $rsnaId; 
					if ($this->MediaPlan->save($mediaPlanData)) {
						// Now import media-plans if user is decided to do so
						if ($mediaPlanImport) {
							$mediaPlanId = $this->MediaPlan->getLastInsertID();
							// 	Get template media-plan-slots for the newly generathed route schedule.
							// To get the template slots first find all media-plan entries for the template route-schedule
							$templateMediaPlans = $this->MediaPlan->findAll(array("RouteScheduleNodeAssoc.route_schedule_id"=>$templateId));
							usort($templateMediaPlans, array("RouteSchedulesController", "nodeOrderSort"));
							foreach ($templateMediaPlans as $templateMediaPlan) {
								if ($rsnaTemplate['RouteScheduleNodeAssoc']['node_id'] == $templateMediaPlan['RouteScheduleNodeAssoc']['node_id'] ) {
									if (count($templateMediaPlan['MediaPlanSlot'])) {
										foreach ($templateMediaPlan['MediaPlanSlot'] as $templateMediaPlanSlot) {
											unset($mediaPlanSlotData); 
											$mediaPlanSlotData['MediaPlanSlot']['id']                          = null; 
											$mediaPlanSlotData['MediaPlanSlot']['media_plan_id']               = $mediaPlanId; 
											$mediaPlanSlotData['MediaPlanSlot']['media_id']                    = $templateMediaPlanSlot['media_id']; 
											$mediaPlanSlotData['MediaPlanSlot']['media_plan_slot_sequence_no'] = $templateMediaPlanSlot['media_plan_slot_sequence_no']; 
											$mediaPlanSlotData['MediaPlanSlot']['media_plan_slot_duration']    = $templateMediaPlanSlot['media_plan_slot_duration'];
											if (!$this->MediaPlanSlot->save($mediaPlanSlotData)) {
												$this->Session->setFlash('Error while importing Mediaplans.', 'message_error');
												return false;
											}
										}											
									}
								}
							}
						}
					} else {
						$allowCommit = false;
						$this->Session->setFlash('Unable to save Media plan for the Route schedule.', 'message_error');
						return false;
					}
					
					
				}
				//Remove the last comma from Route schedule node assoc template Id List
				$rsnaTemplateIdList = substr($rsnaTemplateIdList, 0, -1);
				
				// Create time schedule entries 
				
				/*
				// get list of newly created Route schedule node assoc entries		
				$rsnaIdList = "";
				$rsnas = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$routeScheduleId));
				foreach ($rsnas as $rsna) {
					$rsnaIdList .= $rsna['RouteScheduleNodeAssoc']['id']. ",";
				}
				//Remove the last comma from node List
				$rsnaIdList = substr($rsnaIdList, 0, -1);
				*/
				
				// now get time schedule templates
				$timeScheduleTemplates = $this->TimeSchedule->findAll(array("TimeSchedule.route_schedule_node_assoc_id IN ($rsnaTemplateIdList)"));
				usort($timeScheduleTemplates, array("RouteSchedulesController", "nodeOrderSort"));
				//debug($timeScheduleTemplates);
				// save new time schedule entries
				if(is_array($timeScheduleTemplates)){
					foreach ($timeScheduleTemplates as $timeScheduleTemplate) {
						$timeSchedule['TimeSchedule']['id']                           =  null;
						$timeSchedule['TimeSchedule']['route_schedule_id']            = $routeScheduleId;
						$timeSchedule['TimeSchedule']['route_schedule_node_assoc_id'] = $rsnaMapMatrix[$timeScheduleTemplate['TimeSchedule']['route_schedule_node_assoc_id']];
						$timeSchedule['TimeSchedule']['time_schedule_arrival_time']   = $timeScheduleTemplate['TimeSchedule']['time_schedule_arrival_time'];
						$timeSchedule['TimeSchedule']['time_schedule_arrival_day']    = $timeScheduleTemplate['TimeSchedule']['time_schedule_arrival_day'];
						$timeSchedule['TimeSchedule']['time_schedule_departure_time'] = $timeScheduleTemplate['TimeSchedule']['time_schedule_departure_time'];
						$timeSchedule['TimeSchedule']['time_schedule_departure_day']  = $timeScheduleTemplate['TimeSchedule']['time_schedule_departure_day'];
						$timeSchedule['TimeSchedule']['time_schedule_status']         = 0;
						if(!$this->TimeSchedule->save($timeSchedule)){
							$this->Session->setFlash('Error while importing Route schedule template.', 'message_error');
							return false;
						}
					}
					return true;
				}
			} else {
				$this->Session->setFlash('Please correct errors below.', 'message_error');
				if(!is_array($routeScheduleTemplates = $this->RouteSchedule->generateList())){
					$routeScheduleTemplates = array();
				}
				$routeScheduleTemplates[0] = " None";
				asort($routeScheduleTemplates);
				$this->set('routeScheduleTemplates', $routeScheduleTemplates);
				if(!is_array($routes = $this->RouteSchedule->Route->generateList())){
					$routes = array();
				}
				$this->set('routes', $routes);
				$weekDays = array(
					-1 => 'Daily',
					1 => 'Sunday',
					2 => 'Monday',
					3 => 'Tuesday',
					4 => 'Wednesday',
					5 => 'Thursday',
					6 => 'Friday',
					7 => 'Saturday',
				);
				$this->set('weekDays', $weekDays);
				$this->render();
				exit(0);
			}
		}
		return true;
	}
	
	function view_multiple($id = null) {
		
		$flag = true;
		if (isset($this->params['url']['ids'])) {
			$ids = explode(";", $this->params['url']['ids']);
			if (count($ids) > 0) {
				foreach ($ids as $id) {
					if ($id != null) {
						$id = intval($id); 
						unset($fields);
						$fields['RouteSchedule.id'] = $id;
						if ($this->RouteSchedule->hasAny($fields)) {
							$validIds[] = $id; 
						}
					} 
				}
				if (isset($validIds)) {
					$idList         = implode(",", $validIds);
					$conditions     = array("RouteSchedule.id IN ($idList)");
					$routeSchedules = $this->RouteSchedule->findAll($conditions);
					foreach ($routeSchedules as $i => $routeSchedule) {
						$routeScheduleId = $routeSchedule['RouteSchedule']['id'];
						//--------
						$routeScheduleNodeAssocs = $this->RouteScheduleNodeAssoc->findAll(array('RouteScheduleNodeAssoc.route_schedule_id'=>$routeScheduleId));
						if(empty($routeScheduleNodeAssocs )){
							$routeScheduleNodeAssocs  = array();
						}
						$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$routeScheduleId));
						$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
						usort($routeScheduleNodeAssocs, array("RouteSchedulesController", "nodeOrderSort"));
						$routeSchedules[$i]['TS'] = $routeScheduleNodeAssocs;  
						//-------------
					}
				} else {
					$flag = false;
				}
			} else {
				$flag = false;
			}
		} else {
			$flag = false;
		}
		if ($flag) {
			$weekDays = array(
					-1 => 'Daily',
					1 => 'Sunday',
					2 => 'Monday',
					3 => 'Tuesday',
					4 => 'Wednesday',
					5 => 'Thursday',
					6 => 'Friday',
					7 => 'Saturday',
				);
			$this->set('weekDays', $weekDays);
			$this->set('routeSchedules', $routeSchedules);
		} else {
			$this->Session->setFlash('No Route Schedules selected to view.', 'message_error');
			$this->redirect('/route_schedules/index');
		}
		
	}
	
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $a
	 * @param unknown_type $b
	 * @return unknown
	 */
	function nodeOrderSort($a, $b) {
		
		$nodeA = $a['RouteScheduleNodeAssoc']['node_id'];
		$nodeB = $b['RouteScheduleNodeAssoc']['node_id'];
		
		foreach ($this->routeNodeAssocs as $rna) {
			if ($nodeA == $rna['RouteNodeAssoc']['node_id']) {
				$sequenceNoOfA = $rna['RouteNodeAssoc']['sequence_no'];
			}
			if ($nodeB == $rna['RouteNodeAssoc']['node_id']) {
				$sequenceNoOfB = $rna['RouteNodeAssoc']['sequence_no'];
			}
		}
		
		if ($sequenceNoOfA >= $sequenceNoOfB) {
			return 1;
		} else {
			return -1;
		}
		
	}
	

}
?>